package com.gxc.mall.goods.service.impl;

import com.gxc.mall.common.util.RestControllerResult;
import com.gxc.mall.goods.dto.UserEntity;
import com.gxc.mall.goods.dto.UserParam;
import com.gxc.mall.goods.service.UserService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author GongXincheng
 * @since 2019-09-08 11:47
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private Validator validator;

    /**
     * 测试熔断器.
     */
    @Override
    @HystrixCommand(fallbackMethod = "findUserByIdFallback")
    public ResponseEntity<RestControllerResult<UserEntity>> findUserById(Integer id) {
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON_UTF8);
        header.set("token-gxc", "gxc");
        HttpEntity<Object> httpEntity = new HttpEntity<>(null, header);
        return restTemplate.exchange("http://cloud-mall-service-user/user/{1}", HttpMethod.GET,
                httpEntity, new ParameterizedTypeReference<RestControllerResult<UserEntity>>() {
                }, id);
    }

    public ResponseEntity<RestControllerResult<UserEntity>> findUserByIdFallback(Integer id, Throwable throwable) {
        log.error(throwable.getMessage());
        throwable.printStackTrace();
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Override
    public void validatorObject(UserParam userParam) {
        List<String> list = new ArrayList<>();
        Set<ConstraintViolation<UserParam>> validate = validator.validate(userParam);
        if (validate.size() > 0) {
            validate.forEach(e -> list.add(e.getMessage()));
        }
        System.out.println(String.join("，", list));
    }
}
